package com.ysd.lis.service.bac.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.LabCriticalReport;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.mapper.bac.BacBloodCultrueMapper;
import com.ysd.lis.mapper.bac.BacCultureMediumMapper;
import com.ysd.lis.mapper.bac.BacObserResultMapper;
import com.ysd.lis.mapper.bac.BacTestResultMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.request.bac.BloodCultureTransplantationParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.bac.BacBloodCultrueService;
import com.ysd.lis.service.bac.BacTestCultureMediumService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 血培养结果记录 服务实现类
 * </p>
 *
 * @author cfz
 * @since 2024-08-21
 */
@Service
public class BacBloodCultrueServiceImpl extends ServiceImpl<BacBloodCultrueMapper, BacBloodCultrue> implements BacBloodCultrueService {

    @Autowired
    BacBloodCultrueMapper bacBloodCultrueMapper;
    @Autowired
    BacCultureMediumMapper bacCultureMediumMapper;
    @Autowired
    BacTestCultureMediumService bacTestCultureMediumService;
    @Autowired
    SysRuleSetService sysRuleSetService;//编码规则服务

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Override
    public Result findBacBloodCultrueList(BacBloodCultrue bacBloodCultrue) {
        List<BacBloodCultrue> list = findBacBloodCultrueArray(bacBloodCultrue);
        return Result.succ(1, "请求成功", list);
    }

    @Override
    public List<BacBloodCultrue> findBacBloodCultrueArray(BacBloodCultrue bacBloodCultrue) {
        MPJLambdaWrapper<BacBloodCultrue> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(BacBloodCultrue.class);
        queryWrapper.leftJoin(BacCultureMedium.class, BacCultureMedium::getCode, BacBloodCultrue::getCulMediumNo);
        queryWrapper.eq(BacBloodCultrue::getDelFlag, 0);
        if (BeanUtil.isNotEmpty(bacBloodCultrue.getSampleda())) {
            Timestamp timestamp = new Timestamp(bacBloodCultrue.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            queryWrapper.ge(BacBloodCultrue::getSampleda, startTime);
            queryWrapper.le(BacBloodCultrue::getSampleda, endTime);
            queryWrapper.eq(StrUtil.isNotEmpty(bacBloodCultrue.getSampleNo()), BacTestCultureMedium::getSampleNo, bacBloodCultrue.getSampleNo());
            queryWrapper.eq(StrUtil.isNotEmpty(bacBloodCultrue.getRptGroup()), BacTestCultureMedium::getRptGroup, bacBloodCultrue.getRptGroup());
        }
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getMediumType()), BacCultureMedium::getMediumType, bacBloodCultrue.getMediumType());
        queryWrapper.eq(Objects.nonNull(bacBloodCultrue.getBacPublishStatus()), BacBloodCultrue::getBacPublishStatus, bacBloodCultrue.getBacPublishStatus());
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getId()), BacBloodCultrue::getId, bacBloodCultrue.getId());
        List<BacBloodCultrue> bacBloodCultrues = bacBloodCultrueMapper.selectList(queryWrapper);
        List<Map<String, Object>> samplingSiteList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("samplingSite").getData();

        for (BacBloodCultrue bacBloodCultrue1 : bacBloodCultrues) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(bacBloodCultrue1.getSamplingSite()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(samplingSiteList)) {
                samplingSiteList.stream().filter(a -> a.get("code").equals(bacBloodCultrue1.getSamplingSite())).findFirst().ifPresent(stringObjectMap -> bacBloodCultrue1.setSamplingSiteNa((String) stringObjectMap.get("name")));
            }
        }

        return bacBloodCultrues;
    }

    @Override
    public Result findLastoneBacBloodCultrueList(BacBloodCultrue bacBloodCultrue) {
        MPJLambdaWrapper<BacBloodCultrue> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(BacBloodCultrue::getDelFlag, 0);
        if (BeanUtil.isNotEmpty(bacBloodCultrue.getSampleda())) {
            Timestamp timestamp = new Timestamp(bacBloodCultrue.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            queryWrapper.ge(BacBloodCultrue::getSampleda, startTime);
            queryWrapper.le(BacBloodCultrue::getSampleda, endTime);
            queryWrapper.eq(StrUtil.isNotEmpty(bacBloodCultrue.getSampleNo()), BacTestCultureMedium::getSampleNo, bacBloodCultrue.getSampleNo());
            queryWrapper.eq(StrUtil.isNotEmpty(bacBloodCultrue.getRptGroup()), BacTestCultureMedium::getRptGroup, bacBloodCultrue.getRptGroup());
        }
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getReqNo()), BacTestCultureMedium::getReqNo, bacBloodCultrue.getReqNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getTestFlowNo()), BacTestCultureMedium::getTestFlowNo, bacBloodCultrue.getTestFlowNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getCulMediumNo()), BacTestCultureMedium::getCultureNo, bacBloodCultrue.getCulMediumNo());

        queryWrapper.orderByDesc(BacTestCultureMedium::getCreateTime);
        List<BacBloodCultrue> lst = bacBloodCultrueMapper.selectList(queryWrapper);


        //获取数据字典code获取名称
        List<Map<String, Object>> samplingSiteList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("samplingSite").getData();
        List<Map<String, Object>> culbottleNoList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("incubator").getData();

        for (BacBloodCultrue bacBloodCultrue1 : lst) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(bacBloodCultrue1.getSamplingSite()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(samplingSiteList)) {
                samplingSiteList.stream().filter(a -> a.get("code").equals(bacBloodCultrue1.getSamplingSite())).findFirst().ifPresent(stringObjectMap -> bacBloodCultrue1.setSamplingSiteNa((String) stringObjectMap.get("name")));
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(bacBloodCultrue1.getInstrCode()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(culbottleNoList)) {
                culbottleNoList.stream().filter(a -> a.get("code").equals(bacBloodCultrue1.getInstrCode())).findFirst().ifPresent(stringObjectMap -> bacBloodCultrue1.setInstrNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(lst.isEmpty() ? 0 : 1, lst.isEmpty() ? "查无数据" : "成功", lst.isEmpty() ? null : lst.get(0));
    }

    @Override
    public Result addBacBloodCultrue(BacBloodCultrue bacBloodCultrue) {
        Timestamp testTime = bacBloodCultrue.getTestTime();
        if (ToolsUtils.isEmpty(testTime)) {
            bacBloodCultrue.setTestTime(new Timestamp(System.currentTimeMillis()));
        }
        int i = bacBloodCultrueMapper.insert(bacBloodCultrue);
        if (i > 0) {
            String rptGroup = bacBloodCultrue.getRptGroup();
            String sampleNo = bacBloodCultrue.getSampleNo();
            Timestamp sampleda = bacBloodCultrue.getSampleda();

            LambdaUpdateWrapper<LabMaininfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LabMaininfo::getRptGroup, rptGroup)
                    .eq(LabMaininfo::getSampleda, sampleda)
                    .eq(LabMaininfo::getSampleNo, sampleNo);
            if (bacBloodCultrue.getIsAlarm() == 1) {
                lambdaUpdateWrapper.set(LabMaininfo::getIsAlarm, 1);
            } else {
                lambdaUpdateWrapper.set(LabMaininfo::getIsAlarm, 0);
            }
            labMaininfoMapper.update(null, lambdaUpdateWrapper);

            return Result.succ(1, "新增成功", bacBloodCultrue);
        }
        return Result.fail("新增失败");
    }

    @Override
    public Result deleteBacBloodCultrue(BacBloodCultrue bacBloodCultrue) {
        bacBloodCultrue.setDelFlag(1);
        int i = bacBloodCultrueMapper.updateById(bacBloodCultrue);
        if (i > 0) {
            return Result.succ(1, "删除成功", bacBloodCultrue);
        }
        return Result.fail("删除失败");
    }

    @Autowired
    BacObserResultMapper bacObserResultMapper;
    @Autowired
    BacTestResultMapper bacTestResultMapper;

    @Override
    public Result updateBacBloodCultrue(BacBloodCultrue bacBloodCultrue) {
        int i = bacBloodCultrueMapper.updateById(bacBloodCultrue);
        if (i > 0) {
            String rptGroup = bacBloodCultrue.getRptGroup();
            String sampleNo = bacBloodCultrue.getSampleNo();
            Timestamp sampleda = bacBloodCultrue.getSampleda();

            Timestamp timestamp = new Timestamp(sampleda.getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            Integer isAlarmCnt = 0;
            //查询培养观察结果中是否有危急值数据
            MPJLambdaWrapper<BacObserResult> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.eq(BacObserResult::getDelFlag, 0)
                    .eq(BacObserResult::getRptGroup, rptGroup)
                    .eq(BacObserResult::getSampleNo, sampleNo)
                    .ge(BacObserResult::getSampleda, startTime)
                    .le(BacObserResult::getSampleda, endTime)
                    .eq(BacObserResult::getIsAlarm, 1);
            Integer obsCnt = bacObserResultMapper.selectCount(queryWrapper);
            isAlarmCnt += obsCnt;

            //查询血培养结果中是否有危急值数据
            MPJLambdaWrapper<BacBloodCultrue> queryWrapperb = new MPJLambdaWrapper<>();
            queryWrapperb.eq(BacBloodCultrue::getDelFlag, 0)
                    .eq(BacBloodCultrue::getRptGroup, rptGroup)
                    .eq(BacBloodCultrue::getSampleNo, sampleNo)
                    .ge(BacBloodCultrue::getSampleda, startTime)
                    .le(BacBloodCultrue::getSampleda, endTime)
                    .eq(BacBloodCultrue::getIsAlarm, 1);
            Integer culCnt = bacBloodCultrueMapper.selectCount(queryWrapperb);
            isAlarmCnt += culCnt;

            //查询细菌结果中是否有危急值数据
            MPJLambdaWrapper<BacTestResult> queryWrapperR = new MPJLambdaWrapper<>();
            queryWrapperR.eq(BacTestResult::getDelFlag, 0)
                    .eq(BacTestResult::getRptGroup, rptGroup)
                    .eq(BacTestResult::getSampleNo, sampleNo)
                    .ge(BacTestResult::getSampleda, startTime)
                    .le(BacTestResult::getSampleda, endTime)
                    .eq(BacTestResult::getIsAlarm, 1);
            Integer rptCnt = bacTestResultMapper.selectCount(queryWrapperR);
            isAlarmCnt += rptCnt;


            LambdaUpdateWrapper<LabMaininfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LabMaininfo::getRptGroup, rptGroup)
                    .eq(LabMaininfo::getSampleda, sampleda)
                    .eq(LabMaininfo::getSampleNo, sampleNo);
            if (isAlarmCnt > 0) {
                lambdaUpdateWrapper.set(LabMaininfo::getIsAlarm, 1);
            } else {
                lambdaUpdateWrapper.set(LabMaininfo::getIsAlarm, 0);
            }
            labMaininfoMapper.update(null, lambdaUpdateWrapper);

            return Result.succ(1, "更新成功", bacBloodCultrue);
        }
        return Result.fail("更新失败");
    }

    /*血培养转种*/
    @Override
    public Result bloodCultureTransplantation(BloodCultureTransplantationParam input) {
        /*插入检验选用培养基组合*/
        if (BeanUtil.isEmpty(input.getBacCultureCombination()) || CollectionUtils.isEmpty(input.getBacCultureCombination().getCultureRelList())) {
            return Result.fail("未配置培养基组合/明细信息");
        }
        List<String> culmdmNos = input.getBacCultureCombination().getCultureRelList().stream().map(BacCultureCombinaRel::getCulMediumNo).collect(Collectors.toList());

        MPJLambdaWrapper<BacCultureMedium> queryWrapper = new MPJLambdaWrapper();
        queryWrapper.eq(BacCultureMedium::getDelFlag, 0);
        queryWrapper.in(BacCultureMedium::getCode, culmdmNos);

        List<BacCultureMedium> relList = bacCultureMediumMapper.selectList(queryWrapper);

        List<BacTestCultureMedium> list = new ArrayList<>();
        List<BacBloodCultrue> bloodCulInfos = new ArrayList<>();
        for (BacCultureCombinaRel m : input.getBacCultureCombination().getCultureRelList()) {

            String a = sysRuleSetService.createRuleCodeList("CultuBarCode", 1).get(0);
            BacTestCultureMedium op = new BacTestCultureMedium();
            op.setReqNo(input.getReqNo());
            op.setCultureNo(m.getCulMediumNo());
            op.setCultureNa(m.getCultrueName());
            op.setAutoNo(a);//根据规则产生条码号
            op.setCultureCombinNo(m.getCombinationNo());
            op.setSeq(Integer.valueOf(m.getOrderNum()));
            op.setKind(input.getBacCultureCombination().getType());
            BacCultureMedium fenty = relList.stream().filter(p -> p.getCode().equals(m.getCulMediumNo())).findFirst().orElse(null);
            if (BeanUtil.isNotEmpty(fenty)) {
                op.setBloodVal(fenty.getWeight());
                op.setCultuMedBarCodeLength(fenty.getContainerBarcodeLength());
                op.setIsAutoPopup(fenty.getAutoWindowScan());
            }
            op.setPrintLabelCount(0);
            op.setIsPrintLabel(0);
            op.setCultureCombinNo(input.getBacCultureCombination().getCode());
            op.setCultureCombinNa(input.getBacCultureCombination().getName());
            op.setTestFlowNo(input.getTestFlowNo());
            op.setRptGroup(input.getRptGroup());
            op.setSampleNo(input.getSampleNo());
            op.setSampleda(input.getSampleda());
            op.setParentId(input.getParentId());
            list.add(op);


            /*插入血培养结果数据*/
            BacBloodCultrue bacBloodCultrue = new BacBloodCultrue();
            bacBloodCultrue.setBarcode(a);//根据规则产生条码号
            bacBloodCultrue.setSampleda(input.getSampleda());
            bacBloodCultrue.setSampleNo(input.getSampleNo());
            bacBloodCultrue.setRptGroup(input.getRptGroup());
            bacBloodCultrue.setReqNo(input.getReqNo());
            bacBloodCultrue.setBottleNo(a);
            bacBloodCultrue.setCulMediumNo(m.getCulMediumNo());
            bacBloodCultrue.setCulMediumNa(m.getCultrueName());
            bacBloodCultrue.setTestFlowNo(input.getTestFlowNo());
            bacBloodCultrue.setTestNodeNo(input.getTestNodeNo());
            bloodCulInfos.add(bacBloodCultrue);
        }

        boolean r = bacTestCultureMediumService.saveBatch(list);

        if (r) {
            r = this.saveBatch(bloodCulInfos);
        }

        return r ? Result.succ(1, "成功", true) : Result.fail("操作失败");
    }

    @Override
    public Result getAlarmResult(BacBloodCultrue bacBloodCultrue) {
        Timestamp timestamp = new Timestamp(bacBloodCultrue.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");

        MPJLambdaWrapper<BacBloodCultrue> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(BacBloodCultrue.class);
        lambdaQueryWrapper.leftJoin(LabCriticalReport.class, LabCriticalReport::getResultId, BacBloodCultrue::getId);
        lambdaQueryWrapper.and(wrapper -> wrapper
                .eq(BacBloodCultrue::getRptGroup, bacBloodCultrue.getRptGroup())//防止格式化
                .eq(BacBloodCultrue::getSampleNo, bacBloodCultrue.getSampleNo())//防止格式化
                .ge(BacBloodCultrue::getSampleda, startTime)//防止格式化
                .le(BacBloodCultrue::getSampleda, endTime));//防止格式化
        lambdaQueryWrapper.eq(BacBloodCultrue::getIsAlarm, 1);
        lambdaQueryWrapper.eq(BacBloodCultrue::getDelFlag, 0);
        lambdaQueryWrapper.isNull(LabCriticalReport::getResultId);
        List<BacBloodCultrue> labRptresults = this.baseMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "成功", labRptresults);
    }

    @Override
    public Result findBacBloodCultrueByMaininfoList(BacBloodCultrue bacBloodCultrue) {
        MPJLambdaWrapper<BacBloodCultrue> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(BacBloodCultrue.class);
        queryWrapper.selectAs("rt1", BacCultureMedium::getMediumTag, BacBloodCultrue::getMediumTag);
        queryWrapper.selectAs("rt1", BacCultureMedium::getCultureBottle, BacBloodCultrue::getCultureBottle);
        queryWrapper.leftJoin(BacCultureMedium.class, "rt1", p -> p.eq(BacCultureMedium::getCode, BacBloodCultrue::getCulMediumNo).eq(BacWorkFlowNode::getDelFlag, 0));

        queryWrapper.eq(BacBloodCultrue::getDelFlag, 0);
        if (BeanUtil.isNotEmpty(bacBloodCultrue.getSampleda())) {
            Timestamp timestamp = new Timestamp(bacBloodCultrue.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            queryWrapper.ge(BacBloodCultrue::getSampleda, startTime);
            queryWrapper.le(BacBloodCultrue::getSampleda, endTime);
            queryWrapper.eq(StrUtil.isNotEmpty(bacBloodCultrue.getSampleNo()), BacTestCultureMedium::getSampleNo, bacBloodCultrue.getSampleNo());
            queryWrapper.eq(StrUtil.isNotEmpty(bacBloodCultrue.getRptGroup()), BacTestCultureMedium::getRptGroup, bacBloodCultrue.getRptGroup());
        }
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getReqNo()), BacTestCultureMedium::getReqNo, bacBloodCultrue.getReqNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getTestFlowNo()), BacTestCultureMedium::getTestFlowNo, bacBloodCultrue.getTestFlowNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacBloodCultrue.getCulMediumNo()), BacTestCultureMedium::getCultureNo, bacBloodCultrue.getCulMediumNo());

        queryWrapper.orderByDesc(BacTestCultureMedium::getCreateTime);
        List<BacBloodCultrue> lst = bacBloodCultrueMapper.selectList(queryWrapper);


//        //获取数据字典code获取名称
//        List<Map<String, Object>> samplingSiteList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("samplingSite").getData();
//        List<Map<String, Object>> culbottleNoList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("incubator").getData();
//
//        for (BacBloodCultrue bacBloodCultrue1 : lst) {
//            if (org.apache.commons.lang3.StringUtils.isNotBlank(bacBloodCultrue1.getSamplingSite()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(samplingSiteList)) {
//                samplingSiteList.stream().filter(a -> a.get("code").equals(bacBloodCultrue1.getSamplingSite())).findFirst().ifPresent(stringObjectMap -> bacBloodCultrue1.setSamplingSiteNa((String) stringObjectMap.get("name")));
//            }
//            if (org.apache.commons.lang3.StringUtils.isNotBlank(bacBloodCultrue1.getInstrCode()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(culbottleNoList)) {
//                culbottleNoList.stream().filter(a -> a.get("code").equals(bacBloodCultrue1.getInstrCode())).findFirst().ifPresent(stringObjectMap -> bacBloodCultrue1.setInstrNa((String) stringObjectMap.get("name")));
//            }
//        }

        return Result.succ(lst);
    }
}
